package com.zk.code.net;

/**
 * Created by zhoukaich on 2018/8/9.
 */

import android.content.Intent;
import android.util.Log;

import com.example.imgrecognition.Model.MediaModel;
import com.example.imgrecognition.Model.ParamModel;

import org.litepal.crud.DataSupport;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GenericFutureListener;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.List;

public class UdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    private ByteBuf megbye;

    public UdpClientHandler(ByteBuf megbye) {
        this.megbye = megbye;
    }

    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        ByteBuf byteBuf = msg.content();
        short pacstart = byteBuf.readShort();  //包头
        int len = byteBuf.readShort();         //长度
        long deviceno = byteBuf.readLong();    //设备号
        long compression = byteBuf.readLong();//压缩率
        int type = byteBuf.readByte()& 0xff;  //区分拍照 0 或者摄像 1  或者上传参数 170
        MediaModel mediaModel = new MediaModel();
        mediaModel.setDeviceno(String.valueOf(deviceno));
        ParamModel pm = new ParamModel();
        if(type==170){
            DataSupport.deleteAll(ParamModel.class);
            pm.setDeviceno(String.valueOf(deviceno));
           // mediaModel.setType(170);
            Long photointerval = byteBuf.readLong();    //时间间隔
            pm.setPhotointerval(String.valueOf(photointerval));
            Double matchdegree = byteBuf.readDouble();  //图像匹配率
            pm.setMatchdegree(String.valueOf(matchdegree));
        }
        int pacType = byteBuf.readByte()& 0xff;  //报文类型
        int seqNum = byteBuf.readByte()& 0xff;   //帧序列号
        int chanelNum = byteBuf.readByte()& 0xff;  //通道号
        int pos = byteBuf.readByte()& 0xff;    //预留位号
        int highPacNum = byteBuf.readByte()& 0xff;  //包数高位
        int lowPacNum = byteBuf.readByte()& 0xff;   //包数低位
        short checkPos = byteBuf.readShort();       //校验位
        int pacEnder = byteBuf.readByte()& 0xff; //报文尾

        if(type == 7){
            mediaModel.setType(0);
            mediaModel.setChannle(chanelNum);
        }else if(type==8){
            mediaModel.setType(1);
            mediaModel.setChannle(chanelNum);
        }
        if(!(compression==0)){
            mediaModel.setCompression(String.valueOf(compression));
            pm.setCompression(String.valueOf(compression));
        }
        pm.saveThrows();
        mediaModel.saveThrows();
        System.out.println("response--->"+deviceno);
        Log.e("response-->",deviceno+"");
        Log.e("type-->",type+"");
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
        ctx.close();
    }

    /**
     * 向服务器发送消息
     *
     * @param msg               按规则拼接的消息串
     * @param inetSocketAddress 目标服务器地址
     */
    public static void sendMessage(final String msg, final InetSocketAddress inetSocketAddress) {
        if (msg == null) {
            throw new NullPointerException("msg is null");
        }
        // TODO 这一块的msg需要做处理 字符集转换和Bytebuf缓冲区
        senderInternal(datagramPacket(msg, inetSocketAddress));
    }

    /**
     * 发送数据包并监听结果
     *
     * @param datagramPacket
     */
    public static void senderInternal(final DatagramPacket datagramPacket, List<Channel> channelList) {
        for (Channel channel : channelList) {
            if (channel != null) {
                channel.writeAndFlush(datagramPacket).addListener(new GenericFutureListener<ChannelFuture>() {
                    public void operationComplete(ChannelFuture future)
                            throws Exception {
                        boolean success = future.isSuccess();

                        System.err.println("Sender datagramPacket result : " + success);

                    }
                });
            }
        }
    }

    public static void sendMess(final DatagramPacket datagramPacket, Channel channel) {
        try {
            channel.writeAndFlush(datagramPacket).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 组装数据包
     *
     * @param msg               消息串
     * @param inetSocketAddress 服务器地址
     * @return DatagramPacket
     */
    private static DatagramPacket datagramPacket(String msg, InetSocketAddress inetSocketAddress) {
        ByteBuf dataBuf = Unpooled.copiedBuffer(msg, Charset.forName("UTF-8"));
        DatagramPacket datagramPacket = new DatagramPacket(dataBuf, inetSocketAddress);
        return datagramPacket;
    }

    /**
     * 发送数据包服务器无返回结果
     *
     * @param datagramPacket
     */
    private static void senderInternal(final DatagramPacket datagramPacket) {
        System.err.println("LogPushUdpClient.channel" + UdpClient.channel);
        if (UdpClient.channel != null) {
            UdpClient.channel.writeAndFlush(datagramPacket).addListener(new GenericFutureListener<ChannelFuture>() {
                public void operationComplete(ChannelFuture future)
                        throws Exception {
                    boolean success = future.isSuccess();

                    System.err.println("Sender datagramPacket result : " + success);

                }
            });
        } else {
            throw new NullPointerException("channel is null");
        }
    }

}